package common

import (
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/parnurzeal/gorequest"
	"runtime"
	"sync"
	"time"
)

var logOnce sync.Once
var Loger *log

type log struct {
	Conf Config
}

func (s *log) Get() {
	logOnce.Do(func() {
		err := logs.SetLogger(logs.AdapterFile, fmt.Sprintf(`{"filename":"%s","maxdays":7}`, s.Conf.Get().Log.FilePath))
		if err != nil {
			fmt.Println(err)
			return
		}
		logs.EnableFuncCallDepth(true)
	})
}

func (s *log) Error(f interface{}, v ...interface{}) {
	go dingNotice(Eprintln(f.(string), v...))
	logs.Error(f, v...)
}

func (s *log) Debug(f interface{}, v ...interface{}) {
	logs.Debug(f, v)
}

func (s *log) Info(f interface{}, v ...interface{}) {
	go dingNotice(fmt.Sprintf(f.(string), v...))
	logs.Info(f, v...)
}

func init() {
	Loger = new(log)
	Loger.Get()
}

type dingNoticeReq struct {
	Msgtype string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
}

func dingNotice(content string) {
	req := dingNoticeReq{}
	req.Msgtype = "text"
	req.Text.Content = fmt.Sprintf("ENV:%s 报错：%s", Configer.Runmode, content)
	requestUrl := "https://oapi.dingtalk.com/robot/send?access_token=fba7bdbb379bfd19dc3cc522cecde22f9a5e80237bb6e7ada77355795c37ab67"
	gorequest.New().Post(requestUrl).Timeout(time.Second*5).Set("Content-Type", "application/json").SendStruct(req).End()
}

func Eprintln(format string, v ...interface{}) string {
	var buf [2 << 10]byte
	format = format + " stack:%s"
	v = append(v, string(buf[:runtime.Stack(buf[:], true)]))
	return fmt.Sprintf(format, v...)
}
